/**
 * 
 */
package references2bibtexrcp.command;

import java.io.File;
import java.io.IOException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.ide.FileStoreEditorInput;

import references2bibtexrcp.core.View;
import references2bibtexrcp.pdfToText.Pdf2Text;

/**
 * @author v
 *
 */
public class OpenPDF extends AbstractHandler {

	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		FileDialog fd = new FileDialog(new Shell(Display.getDefault()), SWT.OPEN);
        fd.setText("Open");
        fd.setFilterPath("C:/");
        String[] filterExt = { "*.pdf", "*.txt" };
        fd.setFilterExtensions(filterExt);
        String selected = fd.open();
        
        System.out.println(selected);
        if (selected.endsWith(".pdf")) {
        	System.out.println("PDF FILE");
        	try {
				File fileWrited = new Pdf2Text(new File(selected)).run();
				//file.getName().split("[.]")[0] + ".pxt"
				System.out.println("FILE: " + fileWrited.getName());
				System.out.println("FILE: " + fileWrited.getAbsolutePath());
				IWorkbenchPage page = null;
				try {
					page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				
				try {
					IFileStore fileStore= EFS.getStore(fileWrited.toURI());
					page.openEditor(new FileStoreEditorInput(fileStore),  EditorsUI.DEFAULT_TEXT_EDITOR_ID);
					IViewPart ref = page.findView(View.ID);
					if (ref != null)
						((View)ref).update();
					
				} catch (PartInitException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (CoreException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
        } else { 
        	System.out.println("TEXT FILE");
        }
        
        return null;
	}

}
